﻿using System.Diagnostics;
using CodeAgent.Host.Functions;
using CodeAgent.Host.Workspace;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.Connectors.OpenAI;

#pragma warning disable SKEXP0010

#pragma warning disable SKEXP0110

namespace CodeAgent.Host.Agents;

public class CodeAgent
{
    public static ChatCompletionAgent CreateCodeAgent(AgentOption option, string userId)
    {
        var kernelBuilder = Kernel.CreateBuilder();

        kernelBuilder.AddOpenAIChatCompletion("gpt-4o-2024-11-20", option.Endpoint, option.ApiKey);

        kernelBuilder.Plugins.AddFromType<FileFunction>();

        var kernel = kernelBuilder.Build();

        const string reviewAgentName = "CodeAgent";
        string reviewInstruction =
            $"""
             当前系统信息：
             - 系统名称：{Environment.OSVersion.Platform}
             - 是否安装python: {IsPythonInstalled}
             - 是否安装java: {IsJavaInstalled()}
             - 是否安装Node.js: {IsNodeInstalled()}
             - 是否安装DotNet: {IsDotNetInstalled()}

             角色名称：CodeAgent
             - 您是一位专业的程序员，擅长多种编程语言，熟练掌握各种编程技巧和工具。您能够帮助用户解决代码编写、调试、优化等方面的问题。
             - 您需要根据用户的需求，提供清晰的代码示例、操作指导，或直接编写符合需求的代码片段，然后提供给其他角色进行部署和测试。
             - 您的代码实现必须是完整的、可运行的，确保用户能够直接使用，只需要提供完整的代码实现即可，对于每一个代码应该在哪个文件中实现，您需要明确指出，并且您的代码应该是最佳实践。
             - 你还需要解决其他提出的代码导致的问题，可能是代码编译错误、运行异常，或者是代码逻辑错误等。
             - 容器代码依赖了其他的库或环境，请提供好依赖，确保代码能够正常运行。
             - 你需要将代码实现的文件放在{WorkspaceContext.GetWorkspacePath(userId)}目录下在创建一个项目名，这个行为需要执行文件操作。
             - 如果你的工作完成请通知管理员。
             """;
        var codeReviewAgent = new ChatCompletionAgent()
        {
            Name = reviewAgentName,
            Instructions = reviewInstruction,
            Kernel = kernel,
            Description = "Docker Agent",
            Arguments = new KernelArguments(new OpenAIPromptExecutionSettings()
            {
                FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(),
            }),
        };

        return codeReviewAgent;
    }

    /// <summary>
    /// 当前是否安装了python,如果安装则返回具体版本号，否则返回空字符串
    /// </summary>
    /// <returns></returns>
    public static string IsPythonInstalled()
    {
        try
        {
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "python",
                    Arguments = "--version",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                }
            };

            var version = string.Empty;

            process.Start();

            while (!process.StandardOutput.EndOfStream)
            {
                version = process.StandardOutput.ReadLine();
            }

            return version;
        }
        catch (Exception)
        {
            return string.Empty;
        }
    }

    /// <summary>
    /// 当前是否安装了java,如果安装则返回具体版本号，否则返回空字符串
    /// </summary>
    /// <returns></returns>
    public static string IsJavaInstalled()
    {
        try
        {
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "java",
                    Arguments = "-version",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                }
            };

            var version = string.Empty;

            process.Start();

            while (!process.StandardOutput.EndOfStream)
            {
                version = process.StandardOutput.ReadLine();
            }

            return version;
        }
        catch (Exception e)
        {
            return string.Empty;
        }
    }

    /// <summary>
    /// 当前是否安装了Node.js,如果安装则返回具体版本号，否则返回空字符串
    /// </summary>
    /// <returns></returns>
    public static string IsNodeInstalled()
    {
        try
        {
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "node",
                    Arguments = "--version",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                }
            };

            var version = string.Empty;

            process.Start();

            while (!process.StandardOutput.EndOfStream)
            {
                version = process.StandardOutput.ReadLine();
            }

            return version;
        }
        catch (Exception e)
        {
            return string.Empty;
        }
    }

    /// <summary>
    /// 当前是否安装了DotNet,如果安装则返回具体版本号，否则返回空字符串
    /// </summary>
    public static string IsDotNetInstalled()
    {
        try
        {
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "dotnet",
                    Arguments = "--version",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                }
            };

            var version = string.Empty;

            process.Start();

            while (!process.StandardOutput.EndOfStream)
            {
                version = process.StandardOutput.ReadLine();
            }

            return version;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            return string.Empty;
        }
    }
}